package initialize

import (
	"context"
	"fmt"
	"sync"

	"github.com/astaxie/beego/logs"
	redis "github.com/go-redis/redis/v9"
)

type RedisClientMgr struct {
	option  Option
	Clients map[int]*redis.Client
	mu      sync.RWMutex
}

// open-connection
func (r *RedisClientMgr) dial(db int) {

	rdb := redis.NewClient(&redis.Options{
		Addr: fmt.Sprintf(
			"%s:%s",
			r.option.RedisOption.Host,
			r.option.RedisOption.Port,
		),
		Password: r.option.RedisOption.Password,
		DB:       db,
	})

	_, err := rdb.Ping(context.TODO()).Result()
	if err != nil {
		logs.Info("[redis] Ping failed...", err)
	}

	r.mu.Lock()
	defer r.mu.Unlock()
	r.Clients[db] = rdb
}

//redis-init
func (r *RedisClientMgr) Init(option Option) {

	r.option = option
	defaultDB := 0
	r.dial(defaultDB)

}

// add-client
func (r *RedisClientMgr) SetClient(db int) {
	r.mu.Lock()
	defer r.mu.Unlock()
	r.dial(db)
}

// get-client
func (r *RedisClientMgr) GetClient(db int) *redis.Client {

	r.mu.RLock()
	_, ok := r.Clients[db]
	r.mu.RUnlock()

	if !ok {
		r.dial(db)
	}
	return r.Clients[db]
}
